package com.kancy.springcloudconfig.factory;

import com.kancy.springcloudconfig.exception.BeanCreateException;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>
 * BeanFactory
 * </p>
 *
 * @author: kancy
 * @date: 2019/10/26 13:36
 **/
public class BeanFactory {
    private static Map<String, Object> beanCache = new ConcurrentHashMap();

    public static Object getBean(String beanName){
        return beanCache.get(beanName);
    }

    public static <T> T getBean(String beanName, Class<T> clazz){
        Object bean = beanCache.get(beanName);
        if (bean == null){
            return null;
        }
        return clazz.cast(bean);
    }


    public static <T> T create(String beanName, Class<T> clazz){
        T bean = null;
        try {
            bean = clazz.newInstance();
        } catch (Exception e) {
            throw new BeanCreateException(e);
        }
        beanCache.put(beanName, bean);
        return bean;
    }
}
